<template>
  <base-page class="base-form" title="答题中" @back="onCancel()">
    <view class="main-box">
      <view class="content-box">
        <view>
          <view style="display: flex;height: 40px;align-items: center">
            <view class="clock">
              <u-icon name="clock" size="36"></u-icon>
            </view>
            <view style="margin-top: 10px; margin-left: 6px">
              <u-count-down :timestamp="timestamp" @change="remind" :color="showColor"></u-count-down>
            </view>
            <view style="margin-top: 7px; position: absolute; right: 18px">
              <button size="mini" type="primary" @click="submitTestPaper">
                交卷
              </button>
            </view>
          </view>
          <u-modal :mask-close-able="true" v-model="showM" @confirm="confirm" ref="uModal" show-cancel-button
            :content="content"></u-modal>

          <view style="height: 1px; background-color: #e5e5e5; margin-top: 8px"></view>

          <view>
            <u-mask :show="modalCard" @click="modalCard = false" :custom-style="customStyle">
              <view>
                <scroll-view :scroll-y="true" :style="{ height: swiperHeight }">
                  <view>
                    <view style="margin: 16px 16px; color: #2979ff">
                      <view>答题卡（点击题目更改答案）</view>
                    </view>
                  </view>
                  <view class="card-options">
                    <view v-for="(subject, index) in subjectList" :key="index" style="display: inline-block">
                      <view class="options-shape" v-if="!subject.userAnswer || subject.userAnswer === ''"
                        @click="appointedSubject(index)" style="background-color: #e5e5e5; display: inline-block">
                        <view class="option-poistion" style="display: inline-block"
                          v-if="(index + 1).toString().length == 1">
                          {{ index + 1 }}
                        </view>
                        <view class="option-poistion2" style="display: inline-block" v-else>
                          {{ index + 1 }}
                        </view>
                      </view>
                      <view class="options-shape" v-else @click="appointedSubject(index)"
                        style="background-color: #09bb07; display: inline-block">
                        <view class="option-poistion" style="display: inline-block"
                          v-if="(index + 1).toString().length == 1">
                          {{ index + 1 }}
                        </view>
                        <view class="option-poistion2" style="display: inline-block" v-else>
                          {{ index + 1 }}
                        </view>
                      </view>
                    </view>
                  </view>
                </scroll-view>
              </view>
            </u-mask>
          </view>

          <form>
            <swiper :current="subjectIndex" @change="swiperChange" :style="{ height: swiperHeight }">
              <swiper-item v-for="(subject, index) in subjectList" :key="subject.id">
                <view v-if="index - subjectIndex >= -1 && index - subjectIndex <= 1">
                  <view>
                    <view class="topic">
                      {{ index + 1 }} .
                      <text v-if="currentType === 1" style="color: #2979ff">(单选题)</text>
                      <text v-else-if="currentType === 2" style="color: #2979ff">(多选题)</text>
                      <text v-else-if="currentType === 3" style="color: #2979ff">(判断题)</text>
                      <text v-else-if="currentType === 4" style="color: #2979ff">(论述题)</text>
                      {{ subject.title }}({{ subject.score }}分)
                    </view>
                  </view>
                  <view>
                    <!-- // 修复单选/判断题答案显示问题 -->
                    <radio-group class="block" @change="radioboxChange" v-if="subject.type === 1 || subject.type === 3">
                      <view class="answer" v-for="option in subject.optionList" :key="option.id">
                        <view>
                          <radio :value="option.content"
                            :checked="subject.userAnswer === option.content ? true : false">
                          </radio>
                        </view>
                        <view class="answer-right">{{ option.id }}.{{ option.content }}</view>
                      </view>
                    </radio-group>
                    <checkbox-group @change="checkboxChange" v-else-if="subject.type === 2">
                      <view class="answer" v-for="option in subject.optionList" :key="option.id">
                        <view>
                          <checkbox :value="option.content" :class="subject.userAnswer && subject.userAnswer.split('&').indexOf(option.content) > -1
                            ? 'checked'
                            : ''
                            " :checked="subject.userAnswer && subject.userAnswer.split('&').indexOf(option.content) > -1
                              ? true
                              : false
                              ">
                          </checkbox>
                        </view>
                        <view class="answer-right">{{ option.id }}.{{ option.content }}</view>
                      </view>
                    </checkbox-group>
                    <view v-if="subject.type === 4">
                      <textarea placeholder="请输入答案(限制500字)" :value="subject.userAnswer" @input="textareaChange"
                        :maxlength="500"
                        style="padding:10px 10px;margin: 10px;border-color: rgb(220, 223, 230);text-align: left;border: 1px solid #dcdfe6;width: 90%;height:400px;border-radius: 4px;}"></textarea>
                    </view>
                  </view>

                  <view v-show="subject.showAnswer" class="margin-top solid-top">
                    <view class="cu-bar">
                      <view class="action text-grey">
                        <text>正确答案：</text>
                        <text class="solid-bottom padding-left text-green">{{
                          subject.answer
                        }}</text>
                      </view>
                    </view>
                    <view class="cu-bar cu-bar-title">
                      <view class="action text-grey">
                        <text>解析：</text>
                      </view>
                    </view>
                    <view class="text-content padding text-grey">
                      {{ subject.explain }}
                    </view>
                  </view>
                </view>
              </swiper-item>
            </swiper>
            <view style="
                height: 1px;
                background-color: #e5e5e5;
                margin-top: 8px;
                box-shadow: 10px 1px 1px #e5e5e5;
              ">
            </view>
            <view style="display: flex">
              <view class="last-question" @click="returnLastQuestion">上一题</view>
              <view style="
                  margin-top: 12px;
                  position: absolute;
                  right: 50%;
                  transform: translateX(50%);
                ">
                <button size="mini" type="primary" @click="showCardModal">
                  答题卡
                </button>
              </view>
              <view class="next-question" @click="goNextQuestion">下一题</view>
            </view>
          </form>
        </view>
      </view>
    </view>
  </base-page>
</template>

<script>
import { TPaperInfoController, Leader } from "@/api";
import { isNumber } from "../../uni_modules/uni-forms/components/uni-forms/utils";
export default {
  data() {
    return {
      currentTimestamp: null,
      scrollMark: 0,
      content: "还有未完成的题目，确定要交卷吗?",
      showM: false,
      title: "",
      currentType: 0,
      swiperHeight: "560px",
      subjectIndex: 0, //跳转索引
      autoRadioNext: true, //判断题、单项题，自动移下一题
      timestamp: 600, //答题倒计时
      showColor: "#000000",
      wh: 0,
      modalCard: false,
      customStyle: {
        "background-color": "#FFFFFF",
      },
      subjectList: [
        {
          userAnswer: "",
        },
      ],
      detailObj: null,
      enterId: null,
    };
  },
  onLoad(option) {
    this.detailObj = JSON.parse(decodeURIComponent(option.obj));
    this.timestamp = Number(this.detailObj.duration) * 60;
    console.log(this.detailObj);
  },
  mounted() {
    this.initData();
    // 添加页面事件监听
    this.addPageEventListeners();
  },
  onUnload() {
    // 移除事件监听
    this.removePageEventListeners();
  },
  methods: {
    // 添加页面事件监听
    addPageEventListeners() {
      // 监听返回按钮事件
      if (typeof uni.onNavigationBarButtonTap === 'function') {
        uni.onNavigationBarButtonTap((res) => {
          if (res.type === 'back') {
            this.onCancel();
          }
        });
      }

      // 监听Android返回键 - 添加兼容性检查
      if (typeof uni.onBackPress === 'function') {
        uni.onBackPress(() => {
          this.onCancel();
          return true; // 阻止默认返回行为
        });
      }

      // 监听页面隐藏
      document.addEventListener('visibilitychange', this.handleVisibilityChange);

      // 尝试监听F12事件（主要针对浏览器环境）
      this.addDevToolsListener();
    },

    // 移除页面事件监听
    removePageEventListeners() {
      if (typeof uni.offNavigationBarButtonTap === 'function') {
        uni.offNavigationBarButtonTap();
      }
      // 添加兼容性检查
      if (typeof uni.offBackPress === 'function') {
        uni.offBackPress();
      }
      document.removeEventListener('visibilitychange', this.handleVisibilityChange);
    },

    // 处理页面可见性变化
    handleVisibilityChange() {
      if (document.hidden) {
        // 页面变为隐藏状态，可能是用户切换了标签页或最小化了窗口
        setTimeout(() => {
          if (document.hidden) {
            this.showExitConfirm();
          }
        }, 100);
      }
    },

    // 监听开发者工具打开
    addDevToolsListener() {
      try {
        // 检测F12键按下 (仅在浏览器环境有效)
        document.addEventListener('keydown', (e) => {
          if (e.key === 'F12') {
            e.preventDefault();
            this.showExitConfirm();
          }
        });

        // 检测元素大小变化（尝试检测开发者工具）
        if (typeof Image !== 'undefined') {
          const element = new Image();
          if (element.__defineGetter__) {
            element.__defineGetter__('id', () => {
              this.showExitConfirm();
            });
            console.log(element);
          }
        }
      } catch (error) {
        // 忽略在移动端环境可能出现的错误
        console.log('开发工具检测功能在当前环境不可用');
      }
    },

    // 显示退出确认框
    showExitConfirm() {
      // 确保只在答题期间显示确认框
      if (this.currentTimestamp > 1) {
        this.showM = true;
      }
    },

    onCancel() {
      // 修改返回按钮逻辑，不直接返回，而是显示确认框
      this.showExitConfirm();
    },

    initData() {
      const obj = {
        paperId: this.detailObj.id,
      };
      TPaperInfoController.getPaper(this, obj)
        .then((res) => {
          this.subjectList = res.tQuestionInfos.map((obj) => {
            return {
              id: obj.id,
              title: obj.title,
              type: obj.types,
              optionList: this.transformOptions(obj.options).optionList,
              answer: obj.correctAnswer,
              userAnswer: "",
              score: obj.score,
            };
          });
          this.currentType = this.subjectList[0].type;
        })
        .catch((e) => { });
    },
    transformOptions(optionsStr) {
      // 1. 按 & 分割字符串
      const optionsArray = optionsStr.split("&");
      // 2. 转换为目标结构
      const optionList = optionsArray.map((content, index) => {
        // 生成字母ID（A, B, C...）
        const id = String.fromCharCode(65 + index); // 65是'A'的ASCII码
        return {
          id,
          content,
        };
      });

      return {
        optionList,
      };
    },
    swiperChange(e) {
      //滑动事件
      let index = e.target.current;
      if (index != undefined) {
        this.subjectIndex = index;
        this.currentType = this.subjectList[index].type;
      }
    },
    textareaChange(e) {
      // 获取当前输入框的值
      const value = e.target.value;
      // 更新当前题目的用户答案
      this.subjectList[this.subjectIndex].userAnswer = value;
      // 这里可以添加字数统计或其他处理逻辑
      // console.log('当前输入字数:', value.length);
    },
    radioboxChange(e) {
      //单选选中
      console.log(e.detail);

      var items = this.subjectList[this.subjectIndex].optionList;
      var values = e.detail.value;
      this.subjectList[this.subjectIndex].userAnswer = values;
      if (
        this.autoRadioNext &&
        this.subjectIndex < this.subjectList.length - 1
      ) {
        this.subjectIndex += 1;
      }
    },
    checkboxChange(e) {
      console.log(e.detail);
      //复选选中
      var items = this.subjectList[this.subjectIndex].optionList;
      var values = e.detail.value;
      // 使用&符号拼接选中的选项
      this.subjectList[this.subjectIndex].userAnswer = values.join('&');
    },
    remind(currentTimestamp) {
      this.currentTimestamp = currentTimestamp;
      if (currentTimestamp == 60) {
        // 剩余1分钟时提醒
        this.showColor = "#F64E4E";
        uni.showToast({
          title: "还有1分钟结束考试，请及时提交...",
          icon: "none",
          duration: 3000
        });
      }
      if (currentTimestamp == 180) {
        // 剩余3分钟时提醒（保留原功能）
        this.showColor = "#F64E4E";
        uni.showToast({
          title: "即将超时，请及时提交...",
          icon: "none",
        });
      }
      if (currentTimestamp == 1) {
        uni.showLoading({
          title: "提交中...",
        });
        this.submitPaper();
      }
    },
    returnLastQuestion() {
      if (this.subjectIndex == 0) {
        uni.showToast({
          title: "已经是第一题",
          icon: "none",
        });
      } else {
        this.subjectIndex -= 1;
      }
    },
    goNextQuestion() {
      if (this.subjectIndex == this.subjectList.length - 1) {
        uni.showToast({
          title: "已经是最后一题",
          icon: "none",
        });
      } else {
        this.subjectIndex += 1;
      }
    },
    showCardModal() {
      this.modalCard = true;
    },
    appointedSubject(index) {
      // 仅设置当前题目索引，不重新初始化数据
      this.subjectIndex = index;
      this.modalCard = false;
    },
    submitTestPaper() {
      let _arr = [];
      this.scrollMark = 0;
      console.log(this.subjectList);

      this.subjectList.forEach((item) => {
        //判单是否有没有做的选择题
        _arr.push(item.userAnswer);
        // 对于多选题，需要比较排序后的答案字符串
        if (item.type === 2 && item.answer && item.userAnswer) {
          // 分割并排序正确答案和用户答案，然后重新拼接进行比较
          const sortedCorrectAnswer = item.answer.split('&').sort().join('&');
          const sortedUserAnswer = item.userAnswer.split('&').sort().join('&');
          if (sortedCorrectAnswer === sortedUserAnswer) {
            this.scrollMark += item.score;
          }
        } else if (item.answer == item.userAnswer) {
          this.scrollMark += item.score;
        }
      });
      console.log(_arr);

      if (_arr.some((val) => !val || val === '')) {
        //true
        this.showM = true;
      } else {
        //false
        this.submitPaper();
      }
    },
    getCurrentDateTime() {
      const now = new Date();

      // 获取各时间组件
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");

      // 组合成目标格式
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    submitPaper() {
      //   const data = {
      //     timeConsuming: this.timestamp - this.currentTimestamp,
      //     score: this.scrollMark,
      //     paperId: this.detailObj.id,
      //   };
      const answerRecords = this.subjectList.map((p) => {
        return {
          questionId: p.id,
          userAnswer: p.userAnswer,
        };
      });
      const obj = {
        answerRecords: answerRecords,
        paperInfo: {
          id: this.detailObj.id,
        },
        tHistoryPaper: {
          timeConsuming: this.timestamp - this.currentTimestamp,
          examinationTime: this.getCurrentDateTime(),
          startTime: this.detailObj.nowStart,
          content: "",
        },
      };

      // return
      // 测试
      TPaperInfoController.submitPaper(this, obj)
        .then((res) => {
          console.log(res);
          console.log(isNumber(res));
          if (isNumber(res)) {
            uni.showToast({
              title: "交卷成功",
              icon: "success",
            });
          }

          uni.navigateTo({
            url:
              "/views/forum/examDetails?stuResult=" +
              encodeURIComponent(
                JSON.stringify({
                  tpName: this.detailObj.name,
                  name: uni.getStorageSync("userInfo").showName,
                  timeConsuming: this.timestamp - this.currentTimestamp,
                  score: res,
                  examinationTime: this.getCurrentDateTime(),
                })
              ),
          });

        })
        .catch((err) => {
          console.error(err);
        });
    },

    confirm() {
      //确定提交试卷吗
      this.showM = false;
      this.submitPaper();
    },
  },
};
</script>

<style lang="less">
.topic {
  margin-top: 13px;
  margin-left: 16px;
  font-size: 16px;
}

.answer {
  display: flex;
  margin-top: 26px;
  margin-left: 16px;

  .answer-right {
    font-size: 14px;
    margin-top: 2px;
    margin-left: 6px;
  }
}

.clock {
  margin-top: 10px;
  margin-left: 6px;
}

.last-question {
  margin-top: 13px;
  margin-left: 16px;
  font-size: 15px;
  color: #2979ff;
}

.next-question {
  margin-top: 13px;
  position: absolute;
  right: 16px;
  font-size: 15px;
  color: #2979ff;
}

.card-options {
  .options-shape {
    width: 36px;
    height: 36px;
    border-radius: 18px;
    position: relative;
    margin-left: 16px;

    .option-poistion {
      position: absolute;
      top: 26%;
      left: 40%;
      transform: translate(50% 50%);
    }

    .option-poistion2 {
      position: absolute;
      top: 26%;
      left: 30%;
      transform: translate(50% 50%);
    }
  }
}

.uni-list-cell {
  justify-content: flex-start;
}
</style>